這裡要來稍微再整理一下待做的功能:
文章的國籍分類
文章的tag功能
接著將分兩部分來完成:
這裡其實有很多種做法,
可以在posts/_form.html.erb中加入select tag,
也可以乾脆新增一個country的model,這樣還能讓使用者新增各國媒體的分類。
不過在這裏我想要先用簡單的用enumerize來做:(枚舉)
先把要的媒體分類列出來:
這裡要先做的事情當然是先新增一個欄位給post:
rails g migration add\_contry\_classification\_to\_posts country\_classification:string
再安裝enumerize這個gem,接著在post.rb裡面加入:
class Post < ActiveRecord::Base
  validates :title, presence: true, length: {maximum: 50}
  extend Enumerize
  enumerize :country_classification, 
  in: %w[Franch Russia Arab Germany Korean Spanish Japan Polish Czech Turkey]
  belongs_to :user
end
然後就可以去i18n裡面設定了:
  enumerize:
    post:
      country_classification:
        Franch: 法媒 
        Russia: 俄媒 
        Arab: 阿媒 
        Germany: 德媒 
        Korean: 韓媒 
        Spanish: 西媒 
        Japan: 日媒 
        Polish: 波蘭媒 
        Czech: 捷克媒 
        Turkey: 土媒
接下來解決完strong parameter之後,再到form裡面加上這個欄位:
  <%= f.select :country_classification, Post.country_classification.options,{}, {class: "form-control"} %>
就大功告成啦!
而我仍然是想讓網站儘量能保有原來的樣子,
所以會新增render_titile這個method在model中。
  def render_title
    if country_classification.present?
      "【#{country_classification.text}】 #{title}"
    else
      "【尚未分類】 #{title}"
    end
  end
再來將index中的post.title替換成post.render_title就可以了!